package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.atguigu.spzx.common.handler.exception.SpzxException;
import com.atguigu.spzx.manager.listener.ExcelListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.common.ResultCodeEnum;
import com.atguigu.spzx.model.dto.excel.CategoryExcelDto;
import com.atguigu.spzx.model.entity.category.Category;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * title:
 * author: zgl
 * date: 2024/1/2
 * description：
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ExcelListener excelListener;

    @Override
    public List<Category> getCategoryByPid(Long parentId) {
        List<Category> categoryList = categoryMapper.getCategoryByPid(parentId);
        //设置hasChildren属性
        if (!CollectionUtils.isEmpty(categoryList)) {
            categoryList.forEach(category -> {
                Boolean hasChildren = categoryMapper.hasChildren(category.getId());
                category.setHasChildren(hasChildren);
            });
        }
        return categoryList;
    }

    @Override
    public void importData(MultipartFile excel) {
        //将excel转换流
        try {
            InputStream is = excel.getInputStream();
            if (is.available() == 0) {
                throw new SpzxException(ResultCodeEnum.EXCEL_UPLOAD_ERROR);
            }
            //创建dto
            //创建监听器
            //读取excel文件
            EasyExcel.read(is).head(CategoryExcelDto.class)
                    .registerReadListener(excelListener)
                    .sheet(0)
                    .doRead();
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.EXCEL_UPLOAD_ERROR, e);
        }
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
           List<CategoryExcelDto> list =  categoryMapper.selectAll();
        //response.setHeader();
            EasyExcel.write(response.getOutputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .head(CategoryExcelDto.class)
                    .sheet(0)
                    .doWrite(list);
        } catch (Exception e) {
            throw new SpzxException(ResultCodeEnum.EXCEL_DOWNLOAD_ERROR,e);
        }
    }
}
